//
//  MLSRefreshView.swift
//  MLSMircoBlog
//
//  Created by 袁航 on 15/8/4.
//  Copyright © 2015年 yuanhang. All rights reserved.
//

import UIKit

class MLSRefreshView: UIRefreshControl {
    // 记录控件尺寸(记录的是负值,方便在KVO中调用)
    private var refreshHeight: CGFloat?
    // 重写endRefresh方法
    override func endRefreshing() {
        super.endRefreshing()
        // 停止动画
        refreshView.stopLoading()
    }
    // 重写构造方法
    override init() {
        super.init()
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // 监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        // 如果控件的frame的y值大于0,直接返回
        if frame.origin.y > 0 {
            return
        }
        
        // 如果控件开始刷新,让圈圈转
        if refreshing {
            refreshView.startLoading()
            return
        }
        
        // 监听frame,当到达到控件尺寸的时候,转动箭头
        if frame.origin.y < refreshHeight && !refreshView.refreshArrowRotateFlag {
            refreshView.refreshArrowRotateFlag = true
        } else if frame.origin.y > refreshHeight && refreshView.refreshArrowRotateFlag {
            refreshView.refreshArrowRotateFlag = false
        }
        
        
    }
    // 设置UI界面
    private func setupUI() {
        // 设置背景颜色
        
        
        // 设置控件高的变量值
        refreshHeight = frame.height * -1
        // KVO监听自身frame
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil)
        // 取消原生的转圈
        tintColor = UIColor.clearColor()
        // 设置约束
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.frame.size)
    }
    
    // MARK:- 懒加载控件
    private lazy var refreshView: MLSRefreshInnerView = {
        let v = MLSRefreshInnerView.refreshView()
        self.addSubview(v)
        return v
    }()
    // 移除监听通知
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
}



// 视图控件XIB创建
class MLSRefreshInnerView: UIView {
    // 定义旋转标记
    // 定义箭头是否旋转标记
    private var refreshArrowRotateFlag = false {
        didSet {
            startRotationArrow()
        }
    }
    // 停止动画
    private func stopLoading() {
        // 停止转圈,更改控件状态
        refreshCircle.layer.removeAllAnimations()
        refreshCircleView.hidden = true
        refreshTipView.hidden = false
    }
    // 加载数据视图
    @IBOutlet weak var refreshCircleView: UIView!
    @IBOutlet weak var refreshCircle: UIImageView!
    // 提示下拉刷新视图
    @IBOutlet weak var refreshTipView: UIView!
    @IBOutlet weak var refreshArrow: UIImageView!
    
    class func refreshView() -> MLSRefreshInnerView {
        return NSBundle.mainBundle().loadNibNamed("MLSRefreshView", owner: nil, options: nil).last as! MLSRefreshInnerView
    }
    // 开始动画
    private func startRotationArrow() {
        // 更改控件状态
        refreshCircleView.hidden = true
        refreshTipView.hidden = false
        // 计算旋转角度(在block动画中,苹果默认会就近原则,定义的角度正负不起作用,从顺时针计算,哪个方向进,走哪个方向)
        let angle = refreshArrowRotateFlag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01)
        // 动画
        UIView.animateWithDuration(0.5) { () -> Void in
            self.refreshArrow.transform = CGAffineTransformRotate(self.refreshArrow.transform, angle)
        }
    }
    
    // 开始加载数据
    private func startLoading() {
        if refreshCircle.layer.animationForKey("rotation") != nil {
            return
        }
        // 更改控件状态
        refreshCircleView.hidden = false
        refreshTipView.hidden = true
        // 开始动画
        let ani = CABasicAnimation(keyPath: "transform.rotation")
        ani.repeatCount = MAXFLOAT
        ani.toValue = 2 * M_PI
        ani.duration = 1
        refreshCircle.layer.addAnimation(ani, forKey: "rotation")
    }
}